// pages/adminBind/index.js
// 在app.json中定义的模板消息ID
var app = getApp();
const TEMPLATE_IDS = {
  ORDER_NOTICE: 'kd_vCXBL7Xww9IUkdYCzAwcaiuUzScrjeXh-GGTvGsM',     // 例如：'ABCD1234xxxx'
};

Page({
  data: {
    status: 'loading', // loading, unbound, needSubscribe, success, error
    errorMsg: '',
    userInfo: null,
    is_admin: false,
  },

  onLoad() {
    this.initPage();
  },

  // 初始化页面
  async initPage() {
    this.setData({ status: 'loading' });
    let self = this;
    try {
      // 1. 自动登录
	  app.util.getUserInfo(function (response) {
	      
	      let aid = '';
	      	  if(!aid){
	      		  aid=wx.getStorageSync('VP_AID',2);
	      	  }
	      		app.mdInit(function (cfg,mine,area) {
	      			self.setData({
	      				cfg: cfg,
	      				mine:mine,
	      				area:area,
	      				main_loaded:true
	      			});
	      			
	      			console.log('mine:',mine)
	      			if(mine.is_admin == 0){				
	      				  self.setData({ status: 'unbind',is_admin:0 });
	      			}else{
	      				self.setData({ status: 'success',is_admin:1 });
	      			}
	      		},{
	      			aid:aid,
	      			fuid:'',
	      			stid:''
	      		},true);
	  });
      
      
      // 2. 检查管理员状态
      // await this.checkAdminStatus();
      
    } catch (error) {
      console.error('初始化失败:', error);
      this.setData({
        status: 'error',
        errorMsg: error.message || '初始化失败，请重试'
      });
    }
  },

  // 请求订阅消息（绑定管理员）
  async requestSubscribeMessage() {
    try {
      // 先请求订阅
      const subscribeRes = await wx.requestSubscribeMessage({
        tmplIds: Object.values(TEMPLATE_IDS)
      });
		console.log('subscribeRes.errMsg:',subscribeRes.errMsg)
      if (subscribeRes.errMsg === 'requestSubscribeMessage:ok') {
        // 订阅成功，调用绑定接口
        await this.bindAdmin();
      } else {
        throw new Error('用户拒绝订阅消息');
      }
    } catch (error) {
      this.setData({
        status: 'error',
        errorMsg: '订阅失败：' + error.message
      });
    }
  },

  // 绑定管理员
  async bindAdmin() {
	  let that = this
    try {
		app.util.request({
			url: 'Setting/bind',
			data: {},
			method:'POST',
			headers: {
				'Content-Type': 'application/json',
			},
			success(res) {
				console.log(res)
				if(res.data.code){
					that.setData({ status: 'success' });
					// 3秒后自动跳转
					setTimeout(() => {
					  that.goToHomePage();
					}, 2000);
				}else{
					that.setData({ status: 'error' });
					that.initPage()
					throw new Error('提交失败请重试');
				}
			}
		})
    } catch (error) {
		that.setData({ status: 'error' });
      throw new Error('绑定消息管理员失败');
    }
  },

  // 跳转到首页
  goToHomePage() {
    wx.switchTab({
      url: '/vp_pz/pages/index/index'
    });
  }
});